package com.df.gamesynctest.net;

import com.df.gamesynctest.entity.Player;
import com.df.gamesynctest.entity.UserManager;
import com.df.gamesynctest.handler.MsgCodecs;
import com.df.gamesynctest.msg.MsgWrapper;
import com.df.gamesynctest.msg.S2C_SyncId;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;
import java.nio.Buffer;
import java.util.concurrent.atomic.AtomicInteger;

@Component
public class Server {

    public static AtomicInteger id = new AtomicInteger(1);
    public static final AttributeKey<Integer> idKey = AttributeKey.newInstance("id");
    ServerBootstrap bootstrap ;
    EventLoopGroup boss;
    EventLoopGroup work ;

    public void start(){
        Thread thread = new Thread(()->{
            try {
                ServerBootstrap bootstrap = new ServerBootstrap();
                EventLoopGroup boss = new NioEventLoopGroup();
                EventLoopGroup work = new NioEventLoopGroup();
                bootstrap.group(boss,work);
                bootstrap.channel(NioServerSocketChannel.class);

                bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        socketChannel.pipeline().addLast(new MsgCodecs());
                    }
                });
                ChannelFuture future = bootstrap.bind(6666);
                future.addListener(future1 -> {
                    if(future1.isSuccess()){
                        System.out.println("服务器启动成功！");
                    }else{
                        System.out.println("服务器启动失败！"+future1.cause().getStackTrace());
                    }
                });
                future.sync();
            }catch (Exception e){
                e.printStackTrace();
            }
        });
        thread.setName("tcpServer");
        thread.setDaemon(true);
        thread.start();
    }




    @PreDestroy
    public void destroy(){
        if(boss!=null){
            boss.shutdownGracefully();
        }
        if(work!=null){
            work.shutdownGracefully();
        }
    }
}
